import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpRequest } from "../../../../service/httpRequest";
import { flyIn } from '../../../../animations/fly-in';
import { FileLoader } from "../../../../service/fileLoader";
declare var $:any;
@Component({
  selector: 'app-role-access',
  templateUrl: './role-access.component.html',
  styleUrls: [
    './role-access.component.css'
  ],
  animations: [
    flyIn
  ]
})
export class RoleAccessComponent implements OnInit {

  id:string = '';
  constructor(
    private activeRoute: ActivatedRoute,
    private httpRequest:HttpRequest,
    private fileLoader:FileLoader) { }

  ngOnInit() {
    this.activeRoute.params.subscribe(
      params=>{
        let that = this;
        this.id = params['roleId'];
        this.fileLoader.LoadFileList([
          'assets/js/kendo.all.min.js',
          'http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.material.min.css',
          'http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.common-material.min.css'],function(){
          that.getData();
        });

      }
    );
  }

  getData(){
    this.httpRequest.sendGet('actions/list', {role_id:this.id}).subscribe(res=>{

      $("#treeview").kendoTreeView({
        checkboxes: {
          checkChildren: true
        },
        check: this.onChecks,

        dataSource:this.parseNodes(res)
      });

    },err=>{});
  }

  save(){
    let str = this.onChecks();
    var strArr = str.split(",");
    strArr.sort();
    let result = [];
    let tempStr = "";
    for(let i in strArr){
      if(strArr[i]!= tempStr){
        result.push(strArr[i]);
        tempStr = strArr[i];
      }
    }
    let endstr = result.join(";");
    console.log(endstr)
    this.httpRequest.sendPost('roles/related',{role_id:this.id,action_ids:endstr},'op').subscribe(
      res => alert("权限关联成功！") , err => {}
    );
  }


  checkedNodeIds(nodes, checkedNodes) {
    for (let i = 0; i < nodes.length; i++) {

      if (nodes[i].checked) {
        if(nodes.parent()!= undefined){
          if(nodes.parent().parent()!=undefined){
            if(nodes.parent().parent().parent()!=undefined){
              checkedNodes.push(nodes[i].id);
              checkedNodes.push(nodes.parent().parent().parent().id);
            }
            checkedNodes.push(nodes[i].id);
            checkedNodes.push(nodes.parent().parent().id);
          }
          checkedNodes.push(nodes[i].id);
          checkedNodes.push(nodes.parent().id);
        }
      }

      if (nodes[i].hasChildren) {
        this.checkedNodeIds(nodes[i].children.view(), checkedNodes);
      }
    }
  }

  onChecks() {

    let checkedNodes = [];
    let treeView = $("#treeview").data("kendoTreeView");
    let message;

      this.checkedNodeIds(treeView.dataSource.view(), checkedNodes);



    if (checkedNodes.length > 0) {
      message =  checkedNodes.join(",");
    } else {
      message = "";
    }

    return message;
  }

  parseNodes (nodes){
    let ns = [];
    //var all_checked = true;
    for(let i = 0; i< nodes.length; i++){
      let node = nodes[i];
      let nd = {};
      nd['id'] = node['id'];
      nd['text'] = node['text'];
      if(node['nodes'] != null || node['nodes'] != undefined){
        let next = this.parseNodes(node['nodes']);
        if(next.length > 0){
          nd['items'] = next;
          nd['expanded'] = true;
        }
      }else if(node['state'] != null && node['state'] != undefined){
        nd['checked'] = true;
      }
      ns[i] = nd;
    }
    return ns;
  }
}
